package com.example.minio_demo.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.*;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.util.StringUtils;

import java.io.InputStream;
import java.net.URISyntaxException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Berry on 2018/12/14.
 */
public class HttpsClientUtil {

    private static final String HTTP = "http";
    private static final String HTTPS = "https";
    private static final RequestConfig requestConfig;
    private static Logger logger = LogManager.getLogger(HttpsClientUtil.class);
    private static SSLConnectionSocketFactory sslsf = null;
    private static PoolingHttpClientConnectionManager sslcm = null;
    public static final String POST = "POST";
    public static final String GET = "GET";

    static {
        int connectTimeout = 5 * 1000;
        int readTimeout = 30 * 1000;
        requestConfig = createReqConfig(connectTimeout, readTimeout);
        try {
            org.apache.http.ssl.SSLContextBuilder builder = new org.apache.http.ssl.SSLContextBuilder();
            // 全部信任 不做身份鉴定
            builder.loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                    return true;
                }
            });
            sslsf = new SSLConnectionSocketFactory(builder.build(), new String[]{"TLSv1.1", "TLSv1", "TLSv1.2", "SSLv3"}, null, NoopHostnameVerifier.INSTANCE);
            Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register(HTTP, new PlainConnectionSocketFactory())
                    .register(HTTPS, sslsf)
                    .build();
            sslcm = new PoolingHttpClientConnectionManager(registry);
            sslcm.setMaxTotal(20000);//max
            sslcm.setDefaultMaxPerRoute(5000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static RequestConfig getRequestConfig(Integer connectTimeout, Integer socketTimeout) {
        if (connectTimeout == null && socketTimeout == null) {
            return requestConfig;
        } else {
            if (connectTimeout == null || connectTimeout <= 0) {
                connectTimeout = 5 * 1000;
            } else {
                connectTimeout = connectTimeout * 1000;
            }
            if (socketTimeout == null || socketTimeout <= 0) {
                socketTimeout = 30 * 1000;
            } else {
                socketTimeout = socketTimeout * 1000;
            }
            return createReqConfig(connectTimeout, socketTimeout);
        }
    }

    private static RequestConfig createReqConfig(int connectTimeout, int socketTimeout) {
        RequestConfig.Builder configBuilder = RequestConfig.custom();
        // 设置连接超时
        configBuilder.setConnectTimeout(connectTimeout);
        // 设置读取超时
        configBuilder.setSocketTimeout(socketTimeout);
        // 设置从连接池获取连接实例的超时
        configBuilder.setConnectionRequestTimeout(10 * 1000);
        // 在提交请求之前 测试连接是否可用
        configBuilder.setStaleConnectionCheckEnabled(true);
        return configBuilder.build();
    }

    /**
     * https All
     *
     * @param builder
     * @param requestMethod
     * @return
     */
    public static String httpsRequestSend(HttpParamBuilder builder, String requestMethod) throws Exception {
        if (POST.equalsIgnoreCase(requestMethod)) {
            return post(builder);
        } else {
            return get(builder);
        }
    }

    public static String post(HttpParamBuilder builder) throws Exception {
        String result = "";
        CloseableHttpClient httpClient = null;
        HttpResponse httpResponse = null;
        try {
            httpClient = getHttpsClient();
            HttpPost httpPost = new HttpPost(builder.getUrl());

            if (builder.getConnectTimeout() != null) {
                httpPost.setConfig(getRequestConfig(builder.getConnectTimeout(), builder.getSocketTimeout()));
            }

            //httpPost.setConfig(getRequestConfig(builder.getConnectTimeout(), builder.getSocketTimeout()));
            // 设置头信息
            if (builder.getHeaders() != null) {
                for (Map.Entry<String, Object> entry : builder.getHeaders().entrySet()) {
                    httpPost.addHeader(entry.getKey(), entry.getValue().toString());
                }
            }
            // 设置请求参数
            if (builder.getParams() != null) {
                List<NameValuePair> formparams = new ArrayList<>();
                for (Map.Entry<String, Object> entry : builder.getParams().entrySet()) {
                    //给参数赋值
                    formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
                }
                UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
                httpPost.setEntity(urlEncodedFormEntity);
            }
            // 设置实体 优先级高
            if (builder.getEntity() != null) {
                httpPost.setEntity(builder.getEntity());
            }

            if (!StringUtils.isEmpty(builder.getJsonParam())) {
                StringEntity entity = new StringEntity(builder.getJsonParam(), "utf-8");
                entity.setContentEncoding("UTF-8");
                httpPost.setEntity(entity);
            }
            httpResponse = httpClient.execute(httpPost);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                HttpEntity resEntity = httpResponse.getEntity();
                result = EntityUtils.toString(resEntity, "UTF-8");
            } else {
                logger.error(builder.getUrl() + "************statusCode:" + statusCode);
            }

        } catch (Exception e) {
            logger.error(e.getMessage() + "*****HttpsClientUtil*****" + builder.getUrl() + "*****", e);
            throw e;
        } finally {
            if (httpResponse != null) {
                EntityUtils.consume(httpResponse.getEntity());
            }
        }
        return result;
    }

    public static String get(HttpParamBuilder builder) throws Exception {
        String result = "";
        CloseableHttpClient httpClient = null;
        HttpResponse httpResponse = null;
        try {
            httpClient = getHttpsClient();
            HttpGet httpGet = null;
            if (null == builder.getParams()) {
                httpGet = new HttpGet(builder.getUrl());
            } else {
                URIBuilder ub = new URIBuilder();
                ub.setPath(builder.getUrl());
                ArrayList<NameValuePair> pairs = new ArrayList<>();
                for (Map.Entry<String, Object> entry : builder.getParams().entrySet()) {
                    //给参数赋值
                    pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
                }
                ub.setParameters(pairs);
                try {
                    httpGet = new HttpGet(ub.build());
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                }
            }
            if (builder.getConnectTimeout() != null) {
                httpGet.setConfig(getRequestConfig(builder.getConnectTimeout(), builder.getSocketTimeout()));
            }

            // 设置头信息
            if (builder.getHeaders() != null) {
                for (Map.Entry<String, Object> entry : builder.getHeaders().entrySet()) {
                    httpGet.addHeader(entry.getKey(), entry.getValue().toString());
                }
            }
            httpResponse = httpClient.execute(httpGet);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                HttpEntity resEntity = httpResponse.getEntity();
                result = EntityUtils.toString(resEntity, "UTF-8");
            } else {
                logger.error(builder.getUrl() + "************statusCode:" + statusCode);
            }

        } catch (Exception e) {
            logger.error(e.getMessage() + "*****HttpsClientUtil*****" + builder.getUrl() + "*****", e);
            throw e;
        } finally {
            if (httpResponse != null) {
                EntityUtils.consume(httpResponse.getEntity());
            }
        }
        return result;
    }

    public static HttpResponse postRetrunResponse(HttpParamBuilder builder) throws Exception {
        String result = "";
        CloseableHttpClient httpClient = null;
        HttpResponse httpResponse = null;
        try {
            httpClient = getHttpsClient();
            HttpPost httpPost = new HttpPost(builder.getUrl());

            if (builder.getConnectTimeout() != null) {
                httpPost.setConfig(getRequestConfig(builder.getConnectTimeout(), builder.getSocketTimeout()));
            }
            // 设置头信息
            if (builder.getHeaders() != null) {
                for (Map.Entry<String, Object> entry : builder.getHeaders().entrySet()) {
                    httpPost.addHeader(entry.getKey(), entry.getValue().toString());
                }
            }
            // 设置请求参数
            if (builder.getParams() != null) {
                List<NameValuePair> formparams = new ArrayList<>();
                for (Map.Entry<String, Object> entry : builder.getParams().entrySet()) {
                    //给参数赋值
                    formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
                }
                UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
                httpPost.setEntity(urlEncodedFormEntity);
            }
            // 设置实体 优先级高
            if (builder.getEntity() != null) {
                httpPost.setEntity(builder.getEntity());
            }

            if (!StringUtils.isEmpty(builder.getJsonParam())) {
                StringEntity entity = new StringEntity(builder.getJsonParam(), "utf-8");
                entity.setContentEncoding("UTF-8");
                httpPost.setEntity(entity);
            }
            httpResponse = httpClient.execute(httpPost);
        } catch (Exception e) {
            logger.error(e.getMessage() + "*****HttpsClientUtil*****" + builder.getUrl() + "*****", e);
            throw e;
        }
        return httpResponse;
    }

    /**
     * code码也返回出去
     */
    public static Map<String, String> post(HttpPost httpPost) throws Exception {
        CloseableHttpClient httpClient = null;
        HttpResponse httpResponse = null;
        InputStream in = null;
        Map<String, String> result = new HashMap<>();
        try {
            httpClient = getHttpsClient();
            httpResponse = httpClient.execute(httpPost);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            result.put("code", String.valueOf(statusCode));
            //if (statusCode == HttpStatus.SC_OK) {
            HttpEntity resEntity = httpResponse.getEntity();
            if (resEntity != null) {
                int len = (int) resEntity.getContentLength();
                byte[] data = new byte[len];
                in = resEntity.getContent();
                //long len = entity.getContentLength();// -1 表示长度未知
                int lenIndex = 0;
                int temp = 0;          //所有读取的内容都使用temp接收
                while ((temp = in.read()) != -1) {    //当没有读取完时，继续读取
                    data[lenIndex] = (byte) temp;
                    lenIndex++;
                }
                result.put("data", new String(data));
            }
/*            } else {
                logger.error("************statusCode:" + statusCode);
            }*/
        } catch (Exception e) {
            logger.error(e.getMessage() + "*****HttpsClientUtil*****" + httpPost.getURI().toString() + "*****", e);
            throw e;
        } finally {
            if (httpResponse != null) {
                EntityUtils.consume(httpResponse.getEntity());
            }
        }
        return result;
    }


    public static byte[] getByteResult(String url, Map<String, Object> params) throws Exception {

        CloseableHttpClient httpClient = null;
        HttpResponse httpResponse = null;
        InputStream in = null;
        try {
            httpClient = getHttpsClient();
            HttpGet httpGet = null;
            if (null == params) {
                httpGet = new HttpGet(url);
            } else {
                URIBuilder ub = new URIBuilder();
                ub.setPath(url);
                ArrayList<NameValuePair> pairs = new ArrayList<>();
                for (Map.Entry<String, Object> entry : params.entrySet()) {
                    //给参数赋值
                    pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
                }
                ub.setParameters(pairs);
                try {
                    httpGet = new HttpGet(ub.build());
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                }
            }
            httpResponse = httpClient.execute(httpGet);

            Header header = httpResponse.getFirstHeader("X-Custom-Message");
            if(header != null){
                String value = header.getValue();
                System.out.println("X-Custom-Message："+value);
            }

            HttpEntity entity = httpResponse.getEntity();
            if (entity != null) {
                int len = (int) entity.getContentLength();
                byte[] data = new byte[len];
                in = entity.getContent();
                int lenIndex = 0;
                int temp = 0;          //所有读取的内容都使用temp接收
                while ((temp = in.read()) != -1) {    //当没有读取完时，继续读取
                    data[lenIndex] = (byte) temp;
                    lenIndex++;
                }
                return data;
            }
        } catch (Exception e) {
            logger.error(e.getMessage() + "*****HttpsClientUtil*****" + url + "*****", e);
            throw e;
        } finally {
            if (httpResponse != null) {
                EntityUtils.consume(httpResponse.getEntity());
            }
        }
        return null;
    }

    public static Map<String, Object> postReturnAll(HttpParamBuilder builder) throws Exception {
        Map<String, Object> result = new HashMap<>();
        CloseableHttpResponse httpResponse = null;
        try {
            CloseableHttpClient httpClient = getHttpsClient();
            HttpPost httpPost = new HttpPost(builder.getUrl());
            if (builder.getConnectTimeout() != null) {
                httpPost.setConfig(getRequestConfig(builder.getConnectTimeout(), builder.getSocketTimeout()));
            }
            // 设置头信息
            if (builder.getHeaders() != null) {
                for (Map.Entry<String, Object> entry : builder.getHeaders().entrySet()) {
                    httpPost.addHeader(entry.getKey(), entry.getValue().toString());
                }
            }
            // 设置请求参数
            if (builder.getParams() != null) {
                List<NameValuePair> formparams = new ArrayList<>();
                for (Map.Entry<String, Object> entry : builder.getParams().entrySet()) {
                    formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
                }
                UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
                httpPost.setEntity(urlEncodedFormEntity);
            }
            // 设置实体 优先级高
            if (builder.getEntity() != null) {
                httpPost.setEntity(builder.getEntity());
            }
            if (!StringUtils.isEmpty(builder.getJsonParam())) {
                StringEntity entity = new StringEntity(builder.getJsonParam(), "utf-8");
                entity.setContentEncoding("UTF-8");
                httpPost.setEntity(entity);
            }
            httpResponse = httpClient.execute(httpPost);
            result.put("statusCode", httpResponse.getStatusLine().getStatusCode());
            result.put("result", EntityUtils.toString(httpResponse.getEntity(), "UTF-8"));
        } catch (Exception e) {
            logger.error(e.getMessage() + "*****HttpsClientUtil*****" + builder.getUrl() + "*****", e);
            throw e;
        } finally {
            if (httpResponse != null) {
                EntityUtils.consume(httpResponse.getEntity());
                httpResponse.close();
            }
        }
        return result;
    }

    private static CloseableHttpClient getHttpsClient() throws Exception {
        CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .setConnectionManager(sslcm)
                .build();
        return httpClient;
    }

    /**
     * 请求体
     * @param builder
     * @return
     * @throws Exception
     */
    public static String httpPostRequestBody(HttpParamBuilder builder) throws Exception {

        Map<String, Object> result = new HashMap<>();
        CloseableHttpResponse httpResponse = null;
        try {
            CloseableHttpClient httpClient = getHttpsClient();
            HttpPost httpPost = new HttpPost(builder.getUrl());
            if (builder.getConnectTimeout() != null) {
                httpPost.setConfig(getRequestConfig(builder.getConnectTimeout(), builder.getSocketTimeout()));
            }
            httpPost.addHeader("Content-type", "application/json");
            // 设置头信息
            if (builder.getHeaders() != null) {
                for (Map.Entry<String, Object> entry : builder.getHeaders().entrySet()) {
                    httpPost.addHeader(entry.getKey(), entry.getValue().toString());
                }
            }
            // 设置请求参数
            if (builder.getParams() != null) {
                httpPost.setEntity(new StringEntity(JSONObject.toJSONString(builder.getParams()),"UTF-8"));
            }
            // 设置实体 优先级高
            if (builder.getEntity() != null) {
                httpPost.setEntity(builder.getEntity());
            }
            if (!StringUtils.isEmpty(builder.getJsonParam())) {
                StringEntity entity = new StringEntity(builder.getJsonParam(), "utf-8");
                entity.setContentEncoding("UTF-8");
                httpPost.setEntity(entity);
            }
            httpResponse = httpClient.execute(httpPost);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                HttpEntity resEntity = httpResponse.getEntity();
                return EntityUtils.toString(resEntity, "UTF-8");
            } else {
                logger.error(builder.getUrl() + "************statusCode:" + statusCode);
            }
            return null;
        } catch (Exception e) {
            logger.error(e.getMessage() + "*****HttpsClientUtil*****" + builder.getUrl() + "*****", e);
            throw e;
        } finally {
            if (httpResponse != null) {
                EntityUtils.consume(httpResponse.getEntity());
                httpResponse.close();
            }
        }
    }

}
